<template>
  <div class="member">
    <el-dialog title="成员管理" v-model="dialogTransfer" width="900px" append-to-body :close-on-click-modal="false"
      @close="closeDialogTransferClick">
      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
          <el-tab-pane label="搜索用户" name="search"></el-tab-pane>
          <el-tab-pane label="用户" name="tabOne"></el-tab-pane>
          <el-tab-pane label="岗位" name="tabThree" v-if="isDept"></el-tab-pane>
          <el-tab-pane label="角色" name="tabFour" v-if="isRole"></el-tab-pane>
          <el-tab-pane label="工作组" name="tabFive" v-if="isOperateGroup"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="transferBox">
        <div class="transfer_left">
          <!-- 部门 -->
          <div v-show="activeName == 'tabOne'" class="left_left">
            <el-tree ref="deptTreeRef" class="mt-2" node-key="id" :data="deptDatas"
              :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" :highlight-current="true"
              @node-click="handleNodeClick" :default-expanded-keys="defaultCheckKeys" />
          </div>
          <!-- 岗位/角色/工作组 -->
          <div v-if="activeName == 'tabThree' || activeName == 'tabFour' || activeName == 'tabFive'" class="left_left">
            <div class="jobName" :class="jobActive == i ? 'jobActive' : ''" v-for="(v, i) in jobList" :key="i"
              @click="tabTwoNameClick(v, i)">
              {{ v.name }}
            </div>
          </div>
          <!-- 用户列表 -->
          <div v-if="activeName !== 'search'" class="left_right">
            <el-table :data="deptPersonList" :key="TableKey" v-loading="leftUserLoading" @row-dblclick="queryUserClick">
              <el-table-column prop="nickName" label="用户名" show-overflow-tooltip>
                <template v-slot="scope">
                  <i v-show="activeName !== 'tabFive'" class="el-icon-user-solid icon_size icon_user"></i>
                  <span :class="activeName == 'tabFive' ? 'nickname-cell' : ''">{{ scope.row.nickName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deptName" :label="activeName == 'tabFive' ? '类型' : '部门'" width="100px">
                <template v-slot="scope">
                  <span v-if="scope.row.deptName">{{ scope.row.deptName }}</span>
                </template>
              </el-table-column>
              <el-table-column width="42">
                <template v-slot="scope">
                  <el-icon v-show="scope.row.checked" style="color: #1989fa">
                    <Check />
                  </el-icon>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 搜索 -->
          <div v-if="activeName == 'search'" style="width: 100%">
            <div style="margin-bottom: 10px">
              <el-input v-model="searchInput" style="width: 200px" @keyup.enter.native="searchUserClick"
                placeholder="请输入要搜索的用户名"></el-input>
              <el-button :icon="Search" @click="searchUserClick" style="margin-left: 6px">搜索</el-button>
            </div>
            <div>
              <el-table :data="searchUserList" style="width: 100%" v-loading="searchUserLoading" :key="TableKey"
                @row-dblclick="queryUserClick">
                <el-table-column prop="nickName" label="用户名" show-overflow-tooltip></el-table-column>
                <el-table-column prop="deptName" label="部门"></el-table-column>
                <el-table-column width="42">
                  <template v-slot="scope">
                    <el-icon v-show="scope.row.checked" style="color: #1989fa">
                      <Check />
                    </el-icon>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 中间操作按钮 -->
        <div class="transfer_center">
          <div>
            <el-button v-show="activeName == 'tabOne'" type="primary" size="small" :icon="DArrowRight"
              :disabled="activeName == 'tabOne' && deptPersonList.length == 0" @click="allrightClick"></el-button>
          </div>
          <div>
            <el-button type="danger" size="small" :disabled="TeamPersonList.length == 0" :icon="Delete"
              @click="deleteTableClick"></el-button>
          </div>
        </div>

        <!-- 右边 -->
        <div class="transfer_right">
          <el-table :data="TeamPersonList">
            <el-table-column prop="nickName" label="用户名">
              <template v-slot="scope">
                <span>
                  <i class="el-icon-user-solid icon_size icon_user"></i>
                  <span>{{ scope.row.nickName }}</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="dept" width="60">
              <template v-slot="scope">
                <div>
                  <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <!-- <i class="el-icon-close closeColor" @click="deptDeletePersonClick(scope.row)"></i> -->
                    <el-icon class="closeColor" @click="deptDeletePersonClick(scope.row)">
                      <Delete />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer create_box">
        <el-button @click="closeDialogTransferClick">取 消</el-button>
        <el-button type="primary" :disabled="TeamPersonList.length == 0" @click="sureDialogTransferClick">确
          定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { Delete, DArrowRight, Search } from '@element-plus/icons-vue'
import api from '@/api/system/user'

// State variables
const deptTreeRef = ref<any>(null)
const dialogTransfer = ref(false)
const activeName = ref<string>('tabOne')
const searchInput = ref<string>('')
const deptDatas = ref<any[]>([])
const jobList = ref<any[]>([])
const deptPersonList = ref<any[]>([])
const searchUserList = ref<any[]>([])
const TeamPersonList = ref<any[]>([])
const TableKey = ref<number>(0)
const leftUserLoading = ref<boolean>(false)
const searchUserLoading = ref<boolean>(false)
const isDept = ref<boolean>(false)
const isRole = ref<boolean>(false)
const isOperateGroup = ref<boolean>(false)
const jobActive = ref<number>(0)
const defaultCheckKeys = ref<any[]>([])
const selectedUserIds = ref<number[]>([])

// Default props for el-tree
const defaultProps = reactive({
  children: 'children',
  label: 'label'
})

const props = defineProps({
  pageType: {
    type: String,
    default: ''
  },
  isOperateGroup: {
    //是否显示操作组
    type: Boolean,
    default: false
  },
  isDept: {
    //是否显示部门
    type: Boolean,
    default: false
  },
  onlyOne: {
    // 只能选择一个用户
    type: Boolean,
    default: false
  },
  isRole: {
    // 是否显示角色
    type: Boolean,
    default: false
  }
})

// Methods
// 打开弹窗
const openDialogTransfer = (selectedUsers = []) => {
  dialogTransfer.value = true
  TeamPersonList.value = selectedUsers
  deptPersonList.value = []
  activeName.value = 'tabOne'
  getTreeSelect()
}
// 关闭弹窗
const closeDialogTransferClick = () => {
  dialogTransfer.value = false
  TeamPersonList.value = []
  deptPersonList.value = []
  activeName.value = 'tabOne'
}

const handleTabClick = (pane: any) => {
  // Handle tab click logic
  searchInput.value = ''
  searchUserList.value = []
}
/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res: any = await api.deptTreeSelectNo()
  deptDatas.value = res.data
  if (deptDatas.value && deptDatas.value.length > 0) {
    defaultCheckKeys.value = [deptDatas.value[0].id] // 默认选中第一个部门
    // 请求第一个部门下的人员
    handleNodeClick(deptDatas.value[0])
    nextTick(() => {
      deptTreeRef.value.setCurrentKey(deptDatas.value[0].id) // 设置默认选中的节点
    })
  }
}
// 获取部门下的人员
const handleNodeClick = async (node: any) => {
  const res = await api.listUserNo({
    deptId: node.id,
    pageNum: 0,
    pageSize: 9999
  })
  if (res.code == 200) {
    deptPersonList.value = res.rows
    deptPersonList.value.forEach((item) => {
      if (TeamPersonList.value.findIndex((i) => i.userId == item.userId) != -1) {
        item.checked = true
      }
    })
  }
}

const tabTwoNameClick = (v: any, i: number) => {
  jobActive.value = i
}

const searchUserClick = async () => {
  // Search user logic
  searchUserLoading.value = true
  const res = await api.listUserNo({
    pageNum: 0,
    pageSize: 9999,
    userName: searchInput.value
  })
  if (res.code == 200) {
    searchUserLoading.value = false
    searchUserList.value = res.rows

    searchUserList.value.forEach((item) => {
      if (TeamPersonList.value.findIndex((i) => i.userId == item.userId) != -1) {
        item.checked = true
      }
    })
  } else {
    searchUserLoading.value = false
  }
}

// 单个选中
const queryUserClick = (row: any) => {
  if (TeamPersonList.value.findIndex((item) => item.userId == row.userId) != -1) {
    return
  }
  TeamPersonList.value.push(row)
  deptPersonList.value.forEach((item) => {
    if (item.userId == row.userId) {
      item.checked = true
    }
  })
  searchUserList.value.forEach((item) => {
    if (item.userId == row.userId) {
      item.checked = true
    }
  })
}
// 全部选中
const allrightClick = () => {
  deptPersonList.value.forEach((item) => {
    item.checked = true
    queryUserClick(item)
  })
}
// 删除全部选中人员
const deleteTableClick = (row: any) => {
  ElMessageBox.confirm('此操作将删除全部用户,是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      TeamPersonList.value = []
      deptPersonList.value = deptPersonList.value.map((item) => {
        return { ...item, checked: false }
      })
      searchUserList.value = searchUserList.value.map((item) => {
        return { ...item, checked: false }
      })
    })
    .catch(() => {
      // catch error
    })
}
// 删除单个选中人员
const deptDeletePersonClick = (row: any) => {
  TeamPersonList.value.forEach((item, index) => {
    if (item.userId == row.userId) {
      row.checked = false
      TeamPersonList.value.splice(index, 1)
    }
  })
  searchUserList.value.forEach((item) => {
    if (item.userId == row.userId) {
      item.checked = false
    }
  })
  deptPersonList.value.forEach((item) => {
    if (item.userId == row.userId) {
      item.checked = false
    }
  })
}
// 确定选中人员
const sureDialogTransferClick = () => {
  if (props.onlyOne && TeamPersonList.value.length > 1) {
    ElMessage.error('只能选择一个成员')
    return
  }
  emit('sureDialogTransferClick', TeamPersonList.value)

  closeDialogTransferClick()
}
const emit = defineEmits(['sureDialogTransferClick'])
defineExpose({
  openDialogTransfer,
  closeDialogTransferClick
})
</script>

<style lang="scss" scoped>
:deep(.nickname-cell) {
  display: inline-block;
  /* 或者 block，如果你想要块级元素 */
  max-width: 100%;
  /* 根据需要调整宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
  /* 如果是 inline-block，可以保持和图标对齐 */
}

:deep(.el-dialog) {
  max-width: 900px !important;
  min-width: 790px !important;
}

:deep(.el-dialog__body) {
  padding: 0 20px 20px;
}

:deep(.el-tabs) {
  margin-bottom: 0;
}

.transferBox {
  display: flex;
  justify-content: space-between;

  .transferGloab {
    height: 400px;
    border: 1px solid #f1f1f1;
    overflow-y: auto;
    overflow-x: auto;
    padding: 6px;
  }

  .transfer_left {
    @extend .transferGloab;
    width: 500px;
    min-width: 500px;
  }

  .transfer_right {
    @extend .transferGloab;
    width: 280px;
    min-width: 280px;
  }

  .transfer_Right_perm {
    width: 100%;

    :deep(.el-input__inner) {
      border: 0px !important;
    }
  }

  .transfer_left {
    display: flex;
    justify-content: space-between;

    .left_left {
      width: 240px;
      height: 385px;
      overflow: auto;
    }

    .left_right {
      height: 100%;
      width: 240px;
      border-left: 1px solid #f1f1f1;
    }

    .jobName {
      color: #606266;
      font-size: 14px;
      margin-bottom: 4px;
      padding: 4px 6px;
      border-radius: 3px;
      cursor: pointer;
    }

    .jobName:hover {
      background-color: #f5f7fa;
    }

    .jobActive {
      background-color: #f5f7fa;
    }
  }

  .transfer_right {
    // width: 30%;
    // min-width: 360px;
    // max-width: 55%;
  }

  .icon_size {
    font-size: 15px;
  }

  .icon_user {
    color: #36a3f7;
  }

  .icon_building {
    color: #f2951c;
  }

  .icon_job {
    color: #f56c6c;
  }

  .icon_role {
    color: #1cbbb4;
  }

  .icon_group {
    color: #8b72f7;
  }

  .transfer_center {
    height: 400px;
    padding: 150px 10px 0px 10px;
    text-align: center;
    font-size: 26px;
  }

  .closeColor {
    margin-top: 6px;
    font-size: 16px;
    cursor: pointer;
  }

  .closeColor:hover {
    color: #f56c6c;
  }

  .allColor {
    margin-top: 6px;
    font-size: 16px;
    cursor: pointer;
  }

  .allColor:hover {
    color: #36a3f7;
  }
}

.create_box {
  text-align: right;
  margin-top: 10px;

  // :deep(.el-button--text) {
  //   padding: 9px 15px;
  //   color: #aaa;
  // }

  // :deep(.el-button--text:hover) {
  //   color: #6698ff;
  // }

  // :deep(.el-button--primary) {
  //   background-color: #6698ff;
  //   border-color: #6698ff;
  // }

  // :deep(.el-button--primary:focus) {
  //   box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  // }

  // :deep(.el-button--primary:hover) {
  //   box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  // }
}
</style>
